<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;


// 搜索统计
class Search extends BaseController
{
    public function index()
    {
        return View::fetch();
    }

    public function load(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        if (isset($get['field']) && isset($get['order'])) {
            if ( !empty($get['field']) && !empty($get['order'])) {
                $field = $get['field'];
                $sort = $get['order'];
            } else {
                $field = 'num';
                $sort = 'desc';
            }
        } else {
            $field = 'num';
            $sort = 'desc';
        }

        $total = Db::name('keys')
            ->group('keystr')
            ->count();

        $rows = Db::name('keys')
            ->group('keystr')
            ->field('keystr, SUM(num) as num')
            ->page($get['page'], $get['limit'])
            ->order("$field", "$sort")
            ->select();

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 数据导出
    public function export()
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '关键词搜索统计数据'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['关键词', '搜索次数']);

        //链接数据库
        $total = Db::name('keys')
            ->group('keystr')
            ->count();

        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::name('keys')
                ->group('keystr')
                ->field('keystr, SUM(num) as num')
                ->order('num', 'desc')
                ->limit($start, $nums)
                ->select()
                ->toArray();
            foreach ($rows as $value) {
                $arr = [
                    $value['keystr'],
                    $value['num'],
                ];
                fputcsv($fp, $arr);
            }
            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }
    }
}